import {Dialog} from "@lowcode/jpaas-common-lib";


export default {
    data(){
        return {}
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"scriptInsertLang",key);
        },
        showInsertScript(item){
            let script=item.condition;
            if(!script){
                return true;
            }
            script ="return " +script ;
            let fn=new Function("mdl",script);
            let rtn=fn(this.mdl);
            return rtn;
        },
        insertScript(script){
            this.$refs.jsMonacoes.insertContent(script);
        },
        /**
         *  插入脚本。
         * @param item
         */
        handInsertScript(item){
            this[item.clickEvent](item.name);
        },
        addInvokeScript() {
            Dialog.openInvokeScriptDialog({
                curVm: this,
                widthHeight: ['800px', '600px']
            }, function (self, data) {
                var ary = JSON.parse(data.params);
                var paramValue = self.getParamValue(ary, false);
                var tmp = paramValue.tmp;
                var strTmp = paramValue.strTmp;
                var str = `/**
                    *${strTmp}
                     * @return ${data.descp}
                     */`;
                if (data.async) {
                    str += `this.invokeScript("${data.alias}",${JSON.stringify(tmp)},function(data){;
                       //data:{success:${self.i18n('isSuccess','是否执行成功')},message:${self.i18n('message','提示信息')},data:${self.i18n('scriptReturnData','脚本返回数据')}}
                    });`
                } else {
                    str += `
                        try{
                            //rtn:{success:${self.i18n('isSuccess','是否执行成功')},message:${self.i18n('message','提示信息')},data:${self.i18n('scriptReturnData','脚本返回数据')}};
                            var rtn= await this.invokeScriptPromise("${data.alias}",${JSON.stringify(tmp)});
                        }
                        catch(e){

                        }`;
                }
                self.$refs.jsMonacoes.insertContent(str);
            })
        },
        addInvokeInterface(){
            Dialog.openSysInterfaceDialog({
                curVm: this,max:true
            },function(self,data){
                var params={};
                var strTmp="";
                if((data.apiDataType=='form' ||data.apiDataType=='json') && data.apiBody) {
                    //请求体参数配置
                    strTmp+=self.getInterfaceParams(params,'bodys',self.i18n('bodys','请求体'),data.apiBody,data.apiDataType == 'json');
                }
                if(data.apiHeaders){
                    //请求头参数配置
                    strTmp+=self.getInterfaceParams(params,'headers',self.i18n('headers','请求头'),data.apiHeaders,false);
                }
                if(data.apiPathParams){
                    //请求路径参数配置
                    strTmp+=self.getInterfaceParams(params,'pathParams',self.i18n('pathParams','路径参数'),data.apiPathParams,false);
                }
                if(data.apiQuery){
                    //查询参数配置
                    strTmp+=self.getInterfaceParams(params,'querys',self.i18n('querys','查询参数'),data.apiQuery,false);
                }
                var str = "\n/**\n" +
                    self.i18n('apiName','接口名称') + data.apiName+"\n"+
                    self.i18n('apiPath','接口路径') + data.apiPath+"\n"+
                    strTmp+
                    " */ \n" +
                    "this.invokeInterface(\"" + (data.apiKey || data.apiId) + "\"," + JSON.stringify(params) + ",function(data){\n" +
                    "   //data:"+self.i18n('apiReturn','接口返回数据')+"\n" +
                    "});";
                self.$refs.jsMonacoes.insertContent(str);
            })
        },
        //选择自定义查询
        addInvokeCustomQuery() {
            Dialog.openCustomDataDialog({
                curVm: this,
                widthHeight: ['800px', '600px']
            }, function (self, data) {
                var async=data.async;
                var whereField = self.getWhereField(JSON.parse(data.whereField));
                var resultField = self.getResultField(JSON.parse(data.resultField));
                var str = `/**
*${whereField.strTmp }
*/`;
                    if(async){
                        str+=`this.invokeCustomQuery("${ data.key}",${JSON.stringify(whereField.tmp)},function(data){
                           //${self.i18n('returnData','返回的数据')} data:[${resultField}]
                        });`
                    }
                    else{
                        str+=`
                        try{
                            //${self.i18n('returnData','返回的数据')} data:[${resultField}]
                            let rtn= await this.invokeCustomQueryPromise("${data.key}",${JSON.stringify(whereField.tmp)});
                        }
                        catch(e){
                        }`
                    }
                    ;
                self.$refs.jsMonacoes.insertContent(str);
            });
        },
        addOpenDialog() {
            Dialog.openFormBoListDialog({
                curVm: this,
                data: {single: true, isDialog: 'YES',isDataGrant:true},
                widthHeight: ['1000px', '600px']
            }, function (self, data,pmtAlias) {
                var obj=data[0];
                var str = "/**\n" +
                    self.i18n('openDialog','打开对话框：')+obj.name +
                    " */\n";
                str += "this.openList(\"" + obj.key + "\",{single:"+(obj.multiSelect=="NO")+(pmtAlias?",pmtAlias:\""+pmtAlias+"\"":"")+"},";
                str += "{max:"+(obj.isMax=="YES")+",widthHeight:['"+obj.width+"px', '"+obj.height+"px']},function(data){\n";
                str += "   //data:"+self.i18n('selectDialogData','对话框选择数据')+"\n";
                str += "});";
                self.$refs.jsMonacoes.insertContent(str);
            })
        },
        getParamValue(ary, isChild) {
            var tmp = {};
            var strTmp = "";
            for (var i = 0; ary && i < ary.length; i++) {
                var obj = ary[i];
                var paramType = obj.paramType;
                if (isChild) {
                    strTmp += " *  @subParam ";
                } else {
                    strTmp += " * @param ";
                }
                strTmp += obj.paramName + " " + obj.paramDescp + " " + obj.paramType + "\n";
                if (!paramType || paramType == 'string') {
                    tmp[obj.paramName] = "";
                } else if (paramType == 'int' || paramType == 'double' ) {
                    tmp[obj.paramName] = 0;
                } else if (paramType == 'date') {
                    tmp[obj.paramName] = null;
                } else if (paramType == 'boolean') {
                    tmp[obj.paramName] = false;
                } else if (paramType == 'obj') {
                    var child = obj.children;
                    var paramValue = this.getParamValue(child, true);
                    tmp[obj.paramName] = paramValue.tmp;
                    strTmp += paramValue.strTmp;
                }
            }
            return {
                tmp: tmp,
                strTmp: strTmp
            };
        },
        getInterfaceParams(rootParams,key,name,paramsStr,isJson){
            var params=JSON.parse(paramsStr);
            if(isJson){
                var getParams=function(array) {
                    return array.filter(function (item) {
                        if (item.paramType == 'object' || item.paramType == 'array') {
                            item.children = getParams(item.children);
                            return item.children.length>0;
                        } else {
                            return item.paramSource == 'param';
                        }
                    })
                }
                let filterArr = getParams(params);
                if (filterArr.length > 0) {
                    var getParamsValue=function(obj){
                        if (obj.paramType == 'object') {
                            var paramsValue={};
                            for(var i=0;i<obj.children.length;i++){
                                var item=obj.children[i];
                                paramsValue[item.paramName]=getParamsValue(item);
                            }
                            return paramsValue;
                        } else if(obj.paramType == 'array') {
                            var paramsValue=[];
                            for(var i=0;i<obj.children.length;i++){
                                var item=obj.children[i];
                                paramsValue.push(getParamsValue(item));
                            }
                            return paramsValue;
                        } else {
                            if(obj.paramType == 'number'){
                                return 0;
                            }else if(obj.paramType == 'boolean'){
                                return false;
                            }else{
                                return "";
                            }
                        }
                    }
                    rootParams[key] = getParamsValue(filterArr[0]);
                    return " @param "+key+" "+name+"\n";
                }
            }else{
                let filterArr = params.filter(item => item.paramSource == 'param');
                if (filterArr.length > 0) {
                    rootParams[key]={};
                    filterArr.map(item=>{
                        rootParams[key][item.paramName]="";
                    });
                    return " @param "+key+" "+name+"\n";
                }
            }
            return "";
        },
        //获取自定义查询返回字段
        getResultField(ary) {
            var str = "{";
            for (var i = 0; ary && i < ary.length; i++) {
                if (i > 0) {
                    str += ",";
                }
                var obj = ary[i];
                str += obj.fieldName;
            }
            str += "}";
            return str;
        },
        //获取自定义查询条件字段
        getWhereField(ary) {
            var tmp = {};
            var strTmp = " * @param ";
            for (var i = 0; ary && i < ary.length; i++) {
                var obj = ary[i];
                var paramType = obj.columnType;
                strTmp += obj.fieldName + " " + paramType + "\n";
                tmp[obj.fieldName] = "";
            }
            return {
                tmp: tmp,
                strTmp: strTmp
            };
        },
        addAjax(name){
            let json={
                "get":`
                    //params ${this.i18n('nullKeyJson','可以为空，可以是一个键值对JSON')}
                    this.getAjax().get(url,params).then(res=>{});
                `,
                "postForm":`//params ${this.i18n('nullKeyJson','可以为空，可以是一个键值对JSON')}
                    this.getAjax().postForm(url,params).then(res=>{});`,
                 "postJson":`//params ${this.i18n('nullKeyJson','可以为空，可以是一个键值对JSON')}
                    this.getAjax().postJson(url,params).then(res=>{});`
            }
            this.$refs.jsMonacoes.insertContent(json[name]);
        },
        addOpenForm(){
            var config={
                curVm: this, widthHeight: ['900px', '600px'],
                data:{params:{}}
            };

            Dialog.openFormDialog(config,(res)=>{
                let script=`
                /**
                *${this.i18n('formParam_1','参数1:对话框别名 ，参数2:对话框名称,参数3：是否只读,')}
                *${this.i18n('formParam_4','参数4：主键,参数5:传递到表单数据，')}
                *${this.i18n('formParam_6','参数6:回调函数,参数7：保存后是否关闭打开的窗口')}
                */
                this.openForm("${res.alias}","${res.name}",false,"",{},function(action,data){
                 console.info(data);
             },true)`;
                this.$refs.jsMonacoes.insertContent(script);
            })
        },
        addOpenCustomPage(){
            var config={
                curVm: this, widthHeight: ['900px', '600px'],
            };
            Dialog.openCustomPageDialog(config,(res)=>{
                let json={};
                let paramDef=res.params || "[]";
                let paramsAry=JSON.parse(paramDef);
                for(let i=0;i<paramsAry.length;i++){
                    let o=paramsAry[i];
                    json[o.value]=o.label;
                }
                let str=JSON.stringify(json);

                let script=`/**
                *${this.i18n('customPageParam_1','参数1:对话框别名 ，参数2:页面参数')}
                */
                let params=${str};
                this.openCustomPage("${res.alias}",params)`;
                this.$refs.jsMonacoes.insertContent(script);
            });
        }
    }
}
